define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'echarts', 'echarts-theme'], function ($, undefined, Backend, Table, Form, Echarts) {
    var store_ids = '';
    var Controller = {
        myChart1: function () {
            // 基于准备好的dom，初始化echarts实例
            let myChart = Echarts.init($('#echarts1')[0], 'walden');
            let origin = [];
            let data = [];

            Config.storePercentNums.map(item => {
                origin[item.name] = [];
                data = [];
                item.data.map(function (res) {
                    data.push(res[0]);
                    origin[item.name].push(res[1]);
                })
                item.data = data;
            })
            // 指定图表的配置项和数据
            let option = {
                title: {
                    text: '门店销售对比'
                },
                legend: {
                    data: Config.storePercentCategory
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                toolbox: {
                    show: true,
                    feature: {
                        dataView: {
                            show: true,
                            readOnly: false
                        },
                        magicType: {
                            show: true,
                            type: ['line', 'bar']
                        },
                        restore: {
                            show: true
                        },
                        saveAsImage: {
                            show: true
                        }
                    }
                },
                tooltip: {
                    show: true,
                    trigger: 'axis',
                    formatter: function (param) {
                        let str = '';
                        param.map(function (item, index) {
                            if (index == 0) {
                                str += item.name + '</br></br>';
                            }
                            str += item.seriesName + '</br>';
                            str += `<span>订单数量：${item.value}个</span>
                                    <span style="margin-left:5px;">订单金额： ${origin[item.seriesName][item.dataIndex]}元</span>
                                </br></br>`;
                        })
                        return str;
                    }
                },
                calculable: true,
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: Config.storePercentAmount
                },
                yAxis: {
                    type: 'value'
                },
                series: Config.storePercentNums
            };
            // 使用刚指定的配置项和数据显示图表。
            myChart.setOption(option);

            var date = '';

            $("#form1 .datetimerange").data("callback", function (start, end) {
                date = start.format(this.locale.format) + " - " + end.format(this.locale.format);
                $(this.element).val(date);
                console.log(date)
                refresh();
            });

            var si = null;

            function refresh() {
                origin = [];
                si && clearTimeout(si);
                si = setTimeout(function () {
                    Fast.api.ajax({
                        url: 'booking/report/index',
                        data: {
                            date: date,
                            type: 2,
                            store_ids: store_ids
                        },
                        loading: false
                    }, function (res) {
                        option.legend.data = res.legend;
                        option.xAxis.data = res.xAxis;
                        res.series.map(item => {
                            origin[item.name] = [];
                            data = [];
                            item.data.map(function (res) {
                                data.push(res[0]);
                                origin[item.name].push(res[1]);
                            })
                            item.data = data;
                        })
                        option.series = res.series;
                        myChart.clear();
                        myChart.setOption(option, true);
                        return false;
                    });
                }, 50);
            }

            return {
                chart: myChart,
                refresh: refresh
            };
        },
        myChart2: function () {
            // 基于准备好的dom，初始化echarts实例
            let myChart = Echarts.init($('#echarts2')[0], 'walden');
            let origin = [];
            let data = [];

            Config.typePercentNums.map(item => {
                origin[item.name] = [];
                data = [];
                item.data.map(function (res) {
                    data.push(res[0]);
                    origin[item.name].push(res[1]);
                })
                item.data = data;
            })
            // 指定图表的配置项和数据
            let option = {
                title: {
                    text: '房型销售对比'
                },
                legend: {
                    data: Config.typePercentCategory
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                toolbox: {
                    show: true,
                    feature: {
                        dataView: {
                            show: true,
                            readOnly: false
                        },
                        magicType: {
                            show: true,
                            type: ['line', 'bar']
                        },
                        restore: {
                            show: true
                        },
                        saveAsImage: {
                            show: true
                        }
                    }
                },
                tooltip: {
                    show: true,
                    trigger: 'axis',
                    formatter: function (param) {
                        let str = '';
                        param.map(function (item, index) {
                            if (index == 0) {
                                str += item.name + '</br></br>';
                            }
                            str += item.seriesName + '</br>';
                            str += `<span>订单数量：${item.value}个</span>
                                    <span style="margin-left:5px;">订单金额： ${origin[item.seriesName][item.dataIndex]}元</span>
                                </br></br>`;
                        })
                        return str;
                    }
                },
                calculable: true,
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: Config.typePercentAmount
                },
                yAxis: {
                    type: 'value'
                },
                series: Config.typePercentNums
            };
            // 使用刚指定的配置项和数据显示图表。
            myChart.setOption(option);

            var date = '';

            $("#form2 .datetimerange").data("callback", function (start, end) {
                date = start.format(this.locale.format) + " - " + end.format(this.locale.format);
                $(this.element).val(date);
                refresh();
            });

            var si = null;

            function refresh() {
                origin = [];
                si && clearTimeout(si);
                si = setTimeout(function () {
                    Fast.api.ajax({
                        url: 'booking/report/index',
                        data: {
                            date: date,
                            type: 1,
                            store_ids: store_ids
                        },
                        loading: false
                    }, function (res) {
                        option.legend.data = res.legend;
                        option.xAxis.data = res.xAxis;
                        res.series.map(item => {
                            origin[item.name] = [];
                            data = [];
                            item.data.map(function (res) {
                                data.push(res[0]);
                                origin[item.name].push(res[1]);
                            })
                            item.data = data;
                        })
                        option.series = res.series;
                        myChart.clear();
                        myChart.setOption(option, true);
                        return false;
                    });
                }, 50);
            }

            return {
                chart: myChart,
                refresh: refresh
            };
        },
        myChart3: function () {

            // 基于准备好的dom，初始化echarts实例
            let myChart = Echarts.init($('#echarts3')[0], 'walden');

            // 指定图表的配置项和数据
            let option = {
                title: {
                    text: '订单趋势',
                    subtext: ''
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['交易额', '订单数']
                },
                toolbox: {
                    show: true,
                    feature: {
                        dataView: {
                            show: true,
                            readOnly: false
                        },
                        magicType: {
                            show: true,
                            type: ['line', 'bar']
                        },
                        restore: {
                            show: true
                        },
                        saveAsImage: {
                            show: true
                        }
                    }
                },
                calculable: true,
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: Config.orderSaleCategory
                },
                yAxis: {},
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                series: [{
                    name: "交易额",
                    type: 'line',
                    smooth: true,
                    areaStyle: {
                        normal: {}
                    },
                    lineStyle: {
                        normal: {
                            width: 1.5
                        }
                    },
                    data: Config.orderSaleAmount
                }, {
                    name: '订单数',
                    type: 'line',
                    data: Config.orderSaleNums,
                    markPoint: {
                        data: [{
                                type: 'max',
                                name: '最大值'
                            },
                            {
                                type: 'min',
                                name: '最小值'
                            }
                        ]
                    },
                    markLine: {
                        data: [{
                            type: 'average',
                            name: '平均值'
                        }]
                    }
                }]
            };
            // 使用刚指定的配置项和数据显示图表。
            myChart.setOption(option);

            var date = '',
                order_type = '';

            $("#form3 .datetimerange").data("callback", function (start, end) {
                date = start.format(this.locale.format) + " - " + end.format(this.locale.format);
                $(this.element).val(date);
                refresh();
            });

            //点击按钮
            $(document).on("click", ".btn-type", function () {
                order_type = $(this).data('type');
                refresh();
            });


            var si = null;

            function refresh() {
                si && clearTimeout(si);
                si = setTimeout(function () {
                    Fast.api.ajax({
                        url: 'booking/report/index',
                        data: {
                            date: date,
                            store_ids: store_ids,
                            type: 0,
                            order_type: order_type
                        },
                        loading: false
                    }, function (res) {
                        option.xAxis.data = res.orderSaleCategory;
                        option.series[0].data = res.orderSaleAmount;
                        option.series[1].data = res.orderSaleNums;
                        myChart.clear();
                        myChart.setOption(option, true);
                        if (res.totalOrderAmount != undefined) {
                            $('#totalOrderAmount').html(res.totalOrderAmount)
                        }
                        if (res.todayOrderAmount != undefined) {
                            $('#todayOrderAmount').html(res.todayOrderAmount)
                        }
                        if (res.todayOrderRatio != undefined) {
                            let dom = $('#todayOrderRatio');
                            dom.html((res.todayOrderRatio > 0 ? '+' : '') + res.todayOrderRatio + '%');
                            dom.attr('title', '昨天：' + res.yesterdayOrderAmount);
                            if (res.todayOrderRatio >= 0) {
                                dom.removeClass('text-danger').addClass('text-success');
                            } else {
                                dom.removeClass('text-success').addClass('text-danger');
                            }
                        }

                        return false;
                    });
                }, 50);
            }

            return {
                chart: myChart,
                refresh: refresh
            };
        },
        index: function () {
            let obj = {}
            obj.chart3 = this.myChart3();
            obj.chart2 = this.myChart2();
            obj.chart1 = this.myChart1();

            $(window).resize(function () {
                for (let i in obj) {
                    obj[i].chart.resize();
                }
            });

            $(document).on('change changed', "#c-store_ids", function () {
                store_ids = $('#c-store_ids').val();
                for (let i in obj) {
                    obj[i].refresh();
                }
            })
            //点击刷新
            $(document).on("click", "a.btn-refresh", function () {
                let val = $(this).data('chart');
                obj[val].chart.resize();
                obj[val].refresh();
            });

            //每隔60s定时刷新图表
            setInterval(function () {
                $(".btn-refresh").trigger("click");
            }, 60000);

            //点击按钮
            $(document).on("click", ".btn-filter", function () {
                var label = $(this).text();
                var obj = $(this).closest("form").find(".datetimerange").data("daterangepicker");
                var dates = obj.ranges[label];
                obj.startDate = dates[0];
                obj.endDate = dates[1];
                obj.clickApply();
            });

            //选项卡切入事件
            $(document).on("click", "#resetecharts", function () {
                setTimeout(function () {
                    $(window).trigger("resize");
                }, 50);
            });

            Form.api.bindevent($('.select-store'));
            Form.api.bindevent($("#form1"));
            Form.api.bindevent($("#form2"));
            Form.api.bindevent($("#form3"));

        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});